package com.erp.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import okhttp3.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.Map;

/**
 * Created by chengxia on 2018/12/5.
 */
public class HttpUtils {
    public static  String doGet(String url,String handkey,String handValue){
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        String result = "";
        try{
            //通过默认配置创建一个httpClient实例
            httpClient = HttpClients.createDefault();
            //创建httpGet远程连接实例
            HttpGet httpGet = new HttpGet(url);
            httpGet.addHeader(handkey, handValue);
            //设置请求头信息
            httpGet.addHeader("Accept", "application/json");
            //配置请求参数
            RequestConfig requestConfig = RequestConfig.custom()
                    .setConnectTimeout(35000) //设置连接主机服务超时时间
                    .setConnectionRequestTimeout(35000)//设置请求超时时间
                    .setSocketTimeout(60000)//设置数据读取超时时间
                    .build();
            //为httpGet实例设置配置
            httpGet.setConfig(requestConfig);

            //执行get请求得到返回对象
            response = httpClient.execute(httpGet);
            //通过返回对象获取返回数据
            HttpEntity entity = response.getEntity();
            //通过EntityUtils中的toString方法将结果转换为字符串，后续根据需要处理对应的reponse code
            result = EntityUtils.toString(entity);
            System.out.println(result);

        }catch (ClientProtocolException e){
            e.printStackTrace();
        }catch (IOException ioe){
            ioe.printStackTrace();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            //关闭资源
            if(response != null){
                try {
                    response.close();
                }catch (IOException ioe){
                    ioe.printStackTrace();
                }
            }
            if(httpClient != null){
                try{
                    httpClient.close();
                }catch (IOException ioe){
                    ioe.printStackTrace();
                }
            }
        }
        return result;
    }
    public static String doPost(String url,String handkey,String handValue,String jsonStr){
        //创建httpClient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String result = "";
        try{
            //创建http请求
            HttpPost httpPost = new HttpPost(url);
            httpPost.addHeader(handkey, handValue);
            httpPost.addHeader("Content-Type", "application/json; charset=utf-8");

            //创建请求内容
           //String jsonStr = "{\"qry_by\":\"name\", \"name\":\"Tim\"}";
            StringEntity entity = new StringEntity(jsonStr, Charset.forName("UTF-8"));
            httpPost.setEntity(entity);
            response = httpClient.execute(httpPost);
            result = EntityUtils.toString(response.getEntity(),"GBK");
           // System.out.println(result);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            //关闭资源
            if(response != null){
                try {
                    response.close();
                }catch (IOException ioe){
                    ioe.printStackTrace();
                }
            }
            if(httpClient != null){
                try{
                    httpClient.close();
                }catch (IOException ioe){
                    ioe.printStackTrace();
                }
            }
        }
        return result;
    }
    public static String doPost0(String url,String jsonStr)throws Exception{
        //创建httpClient对象
        String result = "";
        OkHttpClient client=new OkHttpClient();
        MediaType mediaType=MediaType.parse("application/x-www-form-urlencoded");
        RequestBody body=RequestBody.create(mediaType,jsonStr);
        Request request=new Request.Builder().url(url)
                .method("POST",body)
                .addHeader("Content-Type","application/x-www-form-urlencoded")
                //.addHeader("Cookie","S")
                .build();
        Response response=client.newCall(request).execute();
        //解析返回的json数据
        result = response.body().string();
       /* JSONObject jsonObjectTemp = (JSONObject) JSONObject.parse(StringTemp);
        JSONArray jsonResultArrayTemp =   (JSONArray) jsonObjectTemp.get("results");*/

        return result;
    }
    //流程发起专用
    public static String doPost5(String url,String jsonStr,String accesstoken)throws Exception{
        //创建httpClient对象
        String result = "";
        OkHttpClient client=new OkHttpClient();
        MediaType mediaType=MediaType.parse("application/json; charset=utf-8");
        RequestBody body=RequestBody.create(mediaType,jsonStr);
        Request request=new Request.Builder().url(url)
                .method("POST",body)
                .addHeader("Content-Type","application/json; charset=utf-8")
                .addHeader("Authorization","Bearer "+accesstoken)
                //.addHeader("Cookie","S")
                .build();
        Response response=client.newCall(request).execute();
        //解析返回的json数据
        result = response.body().string();
       /* JSONObject jsonObjectTemp = (JSONObject) JSONObject.parse(StringTemp);
        JSONArray jsonResultArrayTemp =   (JSONArray) jsonObjectTemp.get("results");*/

        return result;
    }
    public static String doPost2(String url,String jsonStr,String accesstoken){


        //创建httpClient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String result = "";
        try{
            //创建http请求
            HttpPost httpPost = new HttpPost(url);
           // httpPost.addHeader("Content-Type", "application/json; charset=utf-8");
            if(StringUtils.isNotEmpty(accesstoken)){
                httpPost.addHeader("Authorization","Bearer "+accesstoken);

            }

            //创建请求内容
            //String jsonStr = "{\"qry_by\":\"name\", \"name\":\"Tim\"}";
            StringEntity entity = new StringEntity(jsonStr, ContentType.APPLICATION_JSON);
            httpPost.setEntity(entity);
            response = httpClient.execute(httpPost);
            result = EntityUtils.toString(response.getEntity(),"UTF-8");
            // System.out.println(result);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            //关闭资源
             if(response != null){
                try {
                    response.close();
                }catch (IOException ioe){
                    ioe.printStackTrace();
                }
            }
            if(httpClient != null){
                try{
                    httpClient.close();
                }catch (IOException ioe){
                    ioe.printStackTrace();
                }
            }
        }
        return result;
    }
    public static String doPut2(String url,String jsonStr,String accesstoken){
        //创建httpClient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String result = "";
        try{
            //创建http请求
            HttpPut httpPost = new HttpPut(url);
            // httpPost.addHeader("Content-Type", "application/json; charset=utf-8");
            if(StringUtils.isNotEmpty(accesstoken)){
                httpPost.addHeader("Authorization","Bearer "+accesstoken);

            }

            //创建请求内容
            //String jsonStr = "{\"qry_by\":\"name\", \"name\":\"Tim\"}";
            StringEntity entity = new StringEntity(jsonStr, ContentType.APPLICATION_JSON);
            httpPost.setEntity(entity);
            response = httpClient.execute(httpPost);
            result = EntityUtils.toString(response.getEntity(),"UTF-8");
            // System.out.println(result);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            //关闭资源
            if(response != null){
                try {
                    response.close();
                }catch (IOException ioe){
                    ioe.printStackTrace();
                }
            }
            if(httpClient != null){
                try{
                    httpClient.close();
                }catch (IOException ioe){
                    ioe.printStackTrace();
                }
            }
        }
        return result;
    }
    public static  String doGet2(String url ,String accesstoken,Map<String,String>headers){
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        String result = "";
        try{
            //通过默认配置创建一个httpClient实例
            httpClient = HttpClients.createDefault();
            //创建httpGet远程连接实例
            HttpGet httpGet = new HttpGet(url);
            if(null==headers){
                //设置请求头信息
                httpGet.addHeader("Accept", "application/json;charset=utf-8");
            }else{
                for(Map.Entry<String,String>entry:headers.entrySet()){
                    httpGet.addHeader(entry.getKey(), entry.getValue());
                }
            }

            if(null !=accesstoken){
                httpGet.addHeader("Authorization","Bearer "+accesstoken);
            }
            //配置请求参数
            RequestConfig requestConfig = RequestConfig.custom()
                    .setConnectTimeout(35000) //设置连接主机服务超时时间
                    .setConnectionRequestTimeout(35000)//设置请求超时时间
                    .setSocketTimeout(60000)//设置数据读取超时时间
                    .build();
            //为httpGet实例设置配置
            httpGet.setConfig(requestConfig);

            //执行get请求得到返回对象
            response = httpClient.execute(httpGet);
            //通过返回对象获取返回数据
            HttpEntity entity = response.getEntity();
            //通过EntityUtils中的toString方法将结果转换为字符串，后续根据需要处理对应的reponse code
            result = EntityUtils.toString(entity);
           // System.out.println(result);

        }catch (ClientProtocolException e){
            e.printStackTrace();
        }catch (IOException ioe){
            ioe.printStackTrace();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            //关闭资源
            if(response != null){
                try {
                    response.close();
                }catch (IOException ioe){
                    ioe.printStackTrace();
                }
            }
            if(httpClient != null){
                try{
                    httpClient.close();
                }catch (IOException ioe){
                    ioe.printStackTrace();
                }
            }
        }
        return result;
    }
    public static String doPostJson(String url, String json) {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);
            httpPost.addHeader("Authorization","Bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOlsiYXBpIl0sImNvcnBJZCI6bnVsbCwidXNlcl9pZCI6IjJjOTI4MGEyNjcwNmE3M2EwMTY3MDZhOTNjY2YwMDJiIiwidXNlcl9uYW1lIjoiYWRtaW4iLCJzY29wZSI6WyJyZWFkIl0sIm1vYmlsZSI6ZmFsc2UsImlzQWRtaW4iOnRydWUsImV4cCI6MTYyNzE1MDUyMCwiaXNBcHBBZG1pbiI6ZmFsc2UsImF1dGhvcml0aWVzIjpbIlVTRVIiLCJBVVRIX1NZU1RFTV9NQU5BR0UiXSwianRpIjoiZTE0ODMwMzEtYzU4ZS00ZWU2LTlhNzQtMWY2YjBiMWY2MWRkIiwiY2xpZW50X2lkIjoiYXBpIn0.IVcBRsRpgmDNd0ZUdJR95eoDKC-97tXiNotgRhX_Cdxv6kIxnWr-_iMRrJ8EiB1WrBgM2p2o-z0fsvrF8CYyFM_TX8pP4ZbLtstsQ35InQlcOMCVlH8F6JrxTUZd5PFn7R4DRZicnfGOIOwJl7xTUsLLwyddpLxmVngOwmKIKsDVntr4BOxvF_Y-nesE79VegnAuErs3s3vxMlLsUUKvhayXipMo_0gBxNtH-P2NuZCkkGCTHME27f9C0d1LOj05psQT_aPPCPOIpO2jV2oFvQOKHku14OwoJrb-2m-S-KLcBEQfr-ATudYTUgMYyqib4XxTs1kA8pOH2XkCOdkZrw");
            // 创建请求内容
            StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
            httpPost.setEntity(entity);
            // 执行http请求
            response = httpClient.execute(httpPost);
            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return resultString;
    }
    public static void main(String[] args) throws Exception {
        String url="http://47.100.197.8/api/api/organization/user/add";
        try {
            String json = "{\"departmentId\":\"2c2c80867ab40ee9017aca0657a30636\",\"deptIds\":[],\"username\":\"tt121\",\"name\":\"tt121\",\"roleIds\":[],\"mobile\":\"18653111222\",\"officePhone\":\"\",\"email\":\"\",\"employeeNo\":\"tt121\",\"entryDate\":\"\",\"imgUrl\":\"\",\"imgUrlId\":\"\",\"gender\":\"MALE\"}";

            String result = doPostJson(url, json);

            System.out.println(result);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
